package com.friendc.Controller;

import java.io.*;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.friendc.PrJo.User;
import com.friendc.Service.UserService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.friendc.Util.JdbcUtil;

public class FriendPublishController extends HttpServlet{
	UserService ju = new UserService();
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//前端 发送请求 防止乱码
		req.setCharacterEncoding("utf-8");
		//后台 响应给前端数据 防止乱码
		resp.setCharacterEncoding("utf-8");
		resp.setContentType("application/text; charset=utf-8");
		HttpSession session = req.getSession();//获取session
		User user = (User) session.getAttribute("user");//在session中取出当前登录用户
		String username = user.getUsername();
		String content = "";
		String friendImages = "";
		try {
			//上传的图片保存地址
			String realPath = this.getServletContext().getRealPath("/img/");
			System.out.println("文件保存地址:"+realPath);
			String tempPath = "F:\\java\\LX\\tempPath";
			System.out.println("临时文件目录:"+tempPath);
			File file = new File(realPath);
			if(!file.exists()) {//如果此目录不存在
				System.out.println("此目录不存在，创建一下目录");
				file.mkdir();//创建目录
			}
			//工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();
			//文件上传解析器
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("utf-8");
			if(!ServletFileUpload.isMultipartContent(req)) {//上传的不是文件
				System.out.println("当前上传的不是文件");
				return;
			}
			List<FileItem> items = upload.parseRequest(req);
			for (FileItem fileItem : items) {
				if(fileItem.isFormField()) {//传过来的是普通字段
					content = fileItem.getString("utf-8");
				}else {//传来的是文件
					friendImages = fileItem.getName();//获取文件名字
					InputStream in = fileItem.getInputStream();//读取文件信息
					String path = realPath+"\\"+friendImages;
					System.out.println("文件上传到:"+path);
					OutputStream out = new FileOutputStream(path);//写到另一个文件里
					byte[] b = new byte[256];//每次读写文件长度
					int len = -1;
					while((len = in.read(b)) != -1) {//!=-1的含义是文件未读完
						out.write(b,0,len);
					}
					in.close();
					out.close();
				}
			}
			ju.publishFriendC(username, content, "img/"+friendImages);
			req.getRequestDispatcher("WEB-INF/view/Home.jsp").forward(req, resp);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
	}
}